package com.rq.shuduapp;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import static android.content.Context.WINDOW_SERVICE;
import static android.view.inputmethod.InputMethodManager.HIDE_IMPLICIT_ONLY;

public class AppUtils {
    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion() {
        try {
            PackageManager manager = BASE.getCxt().getPackageManager();
            PackageInfo info = manager.getPackageInfo(BASE.getCxt().getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String sizeShow(int length) {
        DecimalFormat d = new DecimalFormat("#.00");
        if (length < 1024) {
            return length + "B";
        } else if (length < 1024 * 1024) {
            return length / 1024 + "KB";
        } else if (length < 1024 * 1024 * 1024) {
            return d.format(length / (1024 * 1024)) + "MB";
        } else {
            return d.format(length / (1024 * 1024 * 1024)) + "GB";
        }
    }

//    public static void getNetFileSize(final String path, final ActionPasser actionPasser) {
//        if (TextUtils.isEmpty(path)) {
//            return;
//        }
//        final Handler handler = new Handler(Looper.getMainLooper());
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                HttpURLConnection con = null;
//                try {
//                    URL url = new URL(path);
//                    if (path.startsWith("https")) {
//                        con = (HttpsURLConnection) url.openConnection();
//                    } else {
//                        con = (HttpURLConnection) url.openConnection();
//                    }
//                    final int fileLength = con.getContentLength();
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            actionPasser.onAction(0, fileLength);
//                        }
//                    });
//                } catch (MalformedURLException e) {
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } finally {
//                    if (con != null) {
//                        con.disconnect();
//                    }
//                }
//            }
//        }).start();
//    }

    public interface OnAppOnForegroundChangeListener {

        void hide2Back();

        void back2Main();
    }

    public static List<OnAppOnForegroundChangeListener> mOnAppOnForegroundChangeListener = new ArrayList<>();

    public static void addOnForegroundChangeListener(OnAppOnForegroundChangeListener listener) {
        mOnAppOnForegroundChangeListener.add(listener);
    }

    /**
     * 判断app是否处于前台
     *
     * @return
     */
    public static boolean isAppOnForeground(Context context) {

        ActivityManager activityManager = (ActivityManager) context.getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        /**
         * 获取Android设备中所有正在运行的App
         */
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    public static boolean isScreenVertical() {//竖屏 等效为小屏设备
        return BASE.getCxt().getResources()
                .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    // 将px值转换为dip或dp值
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getScreenWidth() {
        //屏幕信息
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) BASE.getCxt()
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        //        screenWidth = dm.widthPixels;
        //        screenHeight = dm.heightPixels;
        return dm.widthPixels;
    }

    public static int getScreenHeight() {
        //屏幕信息
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) BASE.getCxt()
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        //        screenWidth = dm.widthPixels;
        //        screenHeight = dm.heightPixels;
        return dm.heightPixels;
    }

//    public static double showInches() {
//        Point point = new Point();
//        WindowManager windowManager = (WindowManager) BASE.getCxt().getSystemService(WINDOW_SERVICE);
//        windowManager.getDefaultDisplay().getRealSize(point);
//        DisplayMetrics dm = BASE.getCxt().getResources().getDisplayMetrics();
//        double x = Math.pow(point.x / dm.xdpi, 2);
//        double y = Math.pow(point.y / dm.ydpi, 2);
//        double screenInches = Math.sqrt(x + y);
//        LOG.e("AppUtils", "showInches.82:" + dm.densityDpi + "  >> " + dm.density);
//        LOG.e("AppUtils", "getScreenSizeOfDevice2:" + screenInches + " (" + point.x + "," + point.y + ")  dpi:(" + dm.xdpi + "," + dm.ydpi + ")");
//        return screenInches;
//    }

//    public static boolean isMobilePhone() {//当前设备是否为手机
//        int tag = SPUtil.getInt("App.Orientation");
//        if (tag <= 0) {
//            return showInches() < 7;
//        } else if (tag == 1) {
//            return true;
//        } else {
//            return false;
//        }
//    }

    //获取状态栏高度
    public static int getStatusBarHeight() {
        int result = 0;
        int resourceId = BASE.getCxt().getResources()
                .getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = BASE.getCxt().getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 检查设备是否有摄像头
     *
     * @return
     */
    public static boolean hasCamera() {
        return hasBackFacingCamera() || hasFrontFacingCamera();
    }

    private static boolean checkCameraFacing(final int facing) {
        if (getSdkVersion() < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        final int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo info = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, info);
            if (facing == info.facing) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查设备是否有后置摄像头
     *
     * @return
     */
    public static boolean hasBackFacingCamera() {
        final int CAMERA_FACING_BACK = 0;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

    /**
     * 检查设备是否有前置摄像头
     *
     * @return
     */
    public static boolean hasFrontFacingCamera() {
        final int CAMERA_FACING_BACK = 1;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

    public static int getSdkVersion() {
        return Build.VERSION.SDK_INT;
    }

    // 将px值转换为sp值
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static int sp2px(float dpValue) {
        final float scale = BASE.getCxt().getResources().getDisplayMetrics().scaledDensity;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 获取当前本地apk的版本
     *
     * @return
     */
    public static int getVersionCode() {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = BASE.getCxt().getPackageManager()
                    .getPackageInfo(BASE.getCxt().getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取当前本地apk的版本
     *
     * @return
     */
    public static String getVersionName() {
        String versionCode = "";
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionName
            versionCode = BASE.getCxt().getPackageManager()
                    .getPackageInfo(BASE.getCxt().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static String getCpuVersion() {
        String[] abis;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            abis = Build.SUPPORTED_ABIS;
        } else {
            abis = new String[]{Build.CPU_ABI, Build.CPU_ABI2};
        }
        StringBuilder abiStr = new StringBuilder();
        for (String abi : abis) {
            abiStr.append(abi);
            abiStr.append(',');
        }
        return abiStr.toString();
    }

    /**
     * 是否是UI线程
     *
     * @return
     */
    public static boolean isUiThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
//    public static boolean isForeground(Activity activity) {
//        return isForeground(activity, activity.getClass().getName());
//    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
//    public static boolean isForeground(Context context, String className) {
//        if (context == null || TextUtils.isEmpty(className)) {
//            return false;
//        }
//        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
//        if (list != null && list.size() > 0) {
//            ComponentName cpn = list.get(0).topActivity;
//            if (className.equals(cpn.getClassName())) {
//                return true;
//            }
//        }
//        return false;
//    }
    public static void clipContent(String content) {
        ClipboardManager cm = (ClipboardManager) BASE.getCxt()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", content);
        if (cm != null) {
            cm.setPrimaryClip(mClipData);
        }
    }

    public static void hideInput(final Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            LOG.e("AppUtils", "hideInput:activity-> " + activity);
            if (activity.getWindow().getCurrentFocus() != null) {
                if (activity.getWindow().getCurrentFocus() instanceof EditText) {
                    hideInput((EditText) activity.getWindow().getCurrentFocus());
                } else {
                    LOG.e("AppUtils", "hideInput:View-> " + activity.getWindow().getCurrentFocus());
                    InputMethodManager inputManager = (InputMethodManager) activity.getWindow().getContext()
                            .getSystemService(Activity.INPUT_METHOD_SERVICE);
                    inputManager.hideSoftInputFromWindow(activity.getWindow().getCurrentFocus()
                            .getWindowToken(), HIDE_IMPLICIT_ONLY);
                }
            }
        }
    }

    public static void showInput(EditText editText) {
        InputMethodManager imm = (InputMethodManager) BASE.getCxt()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            editText.requestFocus();
            imm.showSoftInput(editText, 0);
        }
    }

    public static void hideInput(EditText editText) {
        InputMethodManager imm = (InputMethodManager) BASE.getCxt()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏软键盘 //
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        //显示软键盘
        //        imm.showSoftInputFromInputMethod(tv.getWindowToken(), 0);
        //        //切换软键盘的显示与隐藏
        //        imm.toggleSoftInputFromWindow(tv.getWindowToken(), 0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static String getPhoneType() {
        return Build.MANUFACTURER + "-" + Build.MODEL;
    }

    public static float dip2px(float dpValue) {
        final float scale = BASE.getCxt().getResources().getDisplayMetrics().density;
        return (dpValue * scale + 0.5f);
    }

    public static boolean isDebug() {
        return BASE.isDebug() || BASE.isRQ();
    }
}
